package org.dev.`as`.project.common.http

import android.os.Bundle
import org.dev.`as`.project.common.route.HiRoute
import org.dev.hi.library.restful.HiInterceptor
import org.dev.hi.library.restful.HiResponse

/**
 * Author WenPing
 * CreateTime 2021/5/11.
 * Description:
 * 根据response的凑得自动路由相关页面；
 * 接口拦截和路由处理
 */
class HttpStatusInterceptor : HiInterceptor {

    override fun intercept(chain: HiInterceptor.Chain): Boolean {
        // 获取拦截器的返回体
        val response = chain.response()
        if (!chain.isRequestPeriod && response != null) {
            val code = response.code
            // 在网络请求过程 做返回码的判断
            when (code) {
                HiResponse.RC_NEED_LOGIN -> {
                        HiRoute.startActivity(
                            null,
                            destination = HiRoute.Destination.ACCOUNT_LOGIN
                        )
                }
                HiResponse.RC_AUTH_TOKEN_EXPIRED,
                (HiResponse.RC_AUTH_TOKEN_INVALID),
                (HiResponse.RC_USER_FORBID) -> {
                    var helpUrl: String? = null
                    if (response.errorData != null) {
                        helpUrl = response.errorData!!.get("helpUrl")
                    }
                    val bundle = Bundle()
                    bundle.run {
                        putString("degrade_title", "非法访问")
                        putString("degrade_desc", response.msg)
                        putString("degrade_action", helpUrl)
                    }
                    //以上情况则跳转到指定页面
                    HiRoute
                        .startActivity(
                            null,
                            bundle = bundle,
                            "/degrade/global/activity"
                        )
                }
            }
        }
        return false
    }
}